<template>
  <el-header class="header">
    <el-header class="header_he">
      <div>
        <img src="@/assets/images/systemManagement/菜单.png" alt="" />
        <span>权限管理</span>
      </div>
      <div>
        <img :src="imgUrl" alt="" />
        <span>{{ userName }}</span>
      </div>
    </el-header>
  </el-header>

  <div class="user-management-page">
    <!-- 顶部操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">+ 添加</el-button>
      <el-button @click="handleRefresh" type="info" ><el-icon><Refresh /></el-icon>刷新</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="roleName" label="用户组" />
      <el-table-column prop="registertime" label="注册时间" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <span :class="scope.row.status == 0 ? 'status-active' : 'status-disabled'">
            {{ scope.row.status==0?"启用":"禁用" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[8, 12,15]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination"
    />

    <!-- 新增/编辑模态框-->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formList"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <!-- 组织机构 -->
        <el-form-item label="组织机构" prop="orginzation">
          <el-select v-model="formList.orginzation" placeholder="请选择组织机构" clearable>
            <el-option
              v-for="item in orgOptions"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 用户名（必填） -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formList.username" placeholder="请输入用户名" clearable />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formList.phone" placeholder="请输入手机号" clearable />
        </el-form-item>

        <!-- 用户组（必填） -->
        <el-form-item label="用户组" prop="roleId">
          <el-select v-model="formList.roleId" placeholder="请选择" clearable>
            <el-option
              v-for="item in userGroupOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 登录密码-->
        <el-form-item label="登录密码" prop="password">
          <el-input
            v-model="formList.password"
            type="password"
            placeholder="请输入密码"
            clearable
          />
          <span class="password-hint">
            密码可由大小写英文字母数字组成，长度为5-16个字符
          </span>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="apassword">
          <el-input
            v-model="formList.apassword"
            type="password"
            placeholder="请再次输入密码"
            clearable
          />
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formList.status">
            <el-radio :value="0">启用</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formList.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, nextTick,watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import yonghuImgUrl from '@/assets/images/systemManagement/菜单.png';
import { getUserList,getRoleList,getAddUser,getUpdateUser,getOrganization} from '@/components/api/PermissionMange';
// import {getOrganization} from '@/components/DeviceMange/Organization'
// 头部数据
const imgUrl = ref(yonghuImgUrl);
const userName = ref("用户手机号");

// 用户表格数据
const tableData = ref([
  {
    org: '1', 
    username: '徐院长',
    phone: '',
    userGroup: '运营',
    registerTime: '2025.07.17',
    status: '启用',
    remark: '',
  },
  {
    org: '1',
    username: 'liyueyue',
    phone: '18731104021',
    userGroup: '财务复核',
    registerTime: '2025.05.07',
    status: '启用',
    remark: '',
  },
  {
    org: '2',
    username: '李学聪',
    phone: '13473956586',
    userGroup: '工程部',
    registerTime: '2024.11.05',
    status: '启用',
    remark: '工程部',
  },
]);
const GetUserList = ()=>{
  const data = {
    pageIndex:currentPage.value,
    pageSize:pageSize.value
  }
  getUserList(data)
  .then(res=>{
    if(res.code==200){
      tableData.value = res.dataset.List;
      total.value = res.dataset.totalSize
    }
  })
}
// 分页配置
const currentPage = ref(1);
const pageSize = ref(8);
const total = ref(43);
GetUserList()
// 模态框状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const saveLoading = ref(false);
const formRef = ref(null);

// 表单数据
const formList = ref({
  orginzation: '',       // 组织机构
  username: '',  // 用户名
  phone: '',     // 手机号
  roleId: '', // 用户组
  password: '',  // 登录密码）
  apassword: '', // 确认密码
  status: '启用',// 默认启用
  remark: ''     // 备注
});

const defaultOrgOptions = [
  { value: '石家庄总公司', label: '石家庄总公司' },
  { value: '第一分公司', label: '第一分公司' },
  { value: '第二分公司', label: '第二分公司' }
];

const orgOptions = ref([...defaultOrgOptions]); // 初始用默认值

const getorgOptions = () => {
  const data = { pageIndex: 1, pageSize: 100 };
  
  getOrganization(data)
    .then(res => {
      console.log(res);
      
      if (!res?.dataset?.dataset?.list || !Array.isArray(res.dataset.dataset.list)) {
        console.warn('数据格式错误，使用默认选项');
        return; // 保留默认值
      }
      // 转换接口数据并覆盖默认值
      orgOptions.value = res.dataset.dataset.list.map(item => ({
        label: item.name || '未知组织',
        value: item.id ?? ''
      }));
    })
    .catch(error => {
      console.error('获取失败，使用默认选项', error);
      // 失败时恢复默认值
      orgOptions.value = [...defaultOrgOptions];
    });
};

getorgOptions();

// 用户组选项
const userGroupOptions = ref([
  { value: '运营', label: '运营' },
  { value: '财务复核', label: '财务复核' },
  { value: '工程部', label: '工程部' },
  { value: '清运部', label: '清运部' },
  { value: '研发部', label: '研发部' }
]);

// 表单验证规则
const rules = reactive({
  orginzation: [{ required: true, message: '请选择组织机构', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  roleId: [{ required: true, message: '请选择用户组', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{5,16}$/, message: '密码需5-16位（字母/数字）', trigger: 'blur' }
  ],
  apassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        value !== formList.value.password ? callback(new Error('两次密码不一致')) : callback();
      }, 
      trigger: 'blur' 
    }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
});

// 分页逻辑
const handleSizeChange = (val) => { pageSize.value = val;GetUserList() };
const handleCurrentChange = (val) => { currentPage.value = val;GetUserList() };

// 打开新增模态框
const handleAdd = () => {
  isEdit.value = false;
  formList.value={
    orginzation: '',       // 组织机构
    username: '',  // 用户名
    phone: '',     // 手机号
    roleId: '', // 用户组
    password: null,  // 登录密码）
    apassword:null, // 确认密码
    status: '启用',// 默认启用
    remark: ''     // 备注
}
  dialogVisible.value = true;
};

// 打开编辑模态框
const handleEdit = (row) => {
  // console.log(row);
  isEdit.value = true;
  formList.value = {
    orginzation: row.orginzation, username: row.username, phone: row.phone,
    roleId: row.roleId, status: row.status, remark: row.remark,id:row.id
// 编辑时密码可选填
  };
  dialogVisible.value = true;
};

// 保存用户（验证+模拟接口）
const handleSave = async () => {
  try {
    await formRef.value.validate(); // 表单验证
    saveLoading.value = true;
    if(isEdit.value){
      getUpdateUser(formList.value)
      .then(res=>{
        if(res.code==200){

        }
      })
    }else{
      getAddUser(formList.value)
      .then(res=>{
        if(res.code==200){
        }
      })
    }
    setTimeout(getFailurelistall,600)
    ElMessage.success(isEdit.value ? '用户编辑成功' : '用户新增成功');
    // console.log(formList.value);
    dialogVisible.value = false;
    // location.reload()
  } catch (error) {
    ElMessage.error(error.message || '操作失败');
  } finally {
    saveLoading.value = false;
  }
};

// 刷新表格
const handleRefresh = () => {
  getFailurelistall()
  ElMessage.info('数据已刷新');
  // 调用接口
};

// 关闭模态框回调
const handleDialogClose = (done) => {
  ElMessageBox.confirm('确认关闭？未保存的内容将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    done();
    formRef.value?.resetFields();
  }).catch(() => {});
};
const qq = ref(null)
// 获取用户组
const getFailurelistall = ()=>{
  const aaa = {
    pageIndex:1,
    pageSize:8
  }
  getRoleList(aaa)
  .then(res=>{
        if (res.code === 200) {
          // console.log(res);
          qq.value = res.dataset.totalSize
          aaa.pageSize= qq.value
          getRoleList(aaa)
          .then(res=>{
                if (res.code === 200) {
                  // console.log(res);
                  
                  const sum = []
                  for(let i=0;i<res.dataset.roleList.length;i++){
                    if(res.dataset.roleList[i].status =="启用"){
                      sum.push(res.dataset.roleList[i])
                    }
                  }
                  userGroupOptions.value = sum
                  console.log(userGroupOptions.value);
                  
                  // tableData.name = res.dataset.name;
                }
          })
          // tableData.name = res.dataset.name;
        }
  })
} 
onMounted(() => {
    getFailurelistall()
})
</script>

<style lang="less" scoped>
/* 头部样式 */
.header {
  background: #fff;
  height: 80px;
  padding: 0 20px;
  border-bottom: 1px solid #ccc;
  box-shadow: 0 1px 2px #ccc;

  .header_he {
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #ccc;

    div {
      display: flex;
      align-items: center;

      img { width: 20px; height: 20px; }
      span { padding: 0 10px; display: inline-block; }
    }
  }
}

/* 用户管理页面容器 */
.user-management-page { 
  padding: 20px; 

}

/* 操作栏 */
.operation-buttons {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格状态颜色 */
.status-active { color: green; }
.status-disabled { color: red; }

/* 分页样式 */
.pagination {
  margin-top: 20px;
  text-align: right;
  flex-direction: row-reverse;
}

/* 模态框表单样式 */
.dialog-form {
  .el-form-item { margin-bottom: 16px; }

  .password-hint {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
    display: inline-block;
  }
}

/* 模态框底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>